<?php
namespace backend\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;


class PostsJoin extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;
    const STATUS = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%posts_join}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
//        return [
//            [['title', 'describe','admin_id','admin_name'], 'trim'],
//            [['title', 'describe','admin_id','admin_name'], 'required','message' => '{attribute}不能为空'],
//        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'title' => '标题',
            'describe' => '简介',
            'admin_id' => '发帖人id',
            'admin_name' => '发帖人',
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [
                'title',
                'describe',
                'sort',
                'banner',
                'video',
            ],
            'create' => [
                'id',
                'posts_id',
                'group_id',
                'item_id',
                'movie_id'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
            'update' => [
                '!id',
                'posts_id',
                'group_id',
                'item_id',
                'movie_id'.
                'status',
                'create_time',
                'update_time',
                'deleted_at',
            ],
        ];
    }

    public static function deleteData($id){
        $model = static::findOne(['id' => $id]);
        if(empty($model)){
            return true;
        }
        $model->deleted_at = time();
        return $model->save();
    }

    /**
     * 更新数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static function saveInfo($data){
//        $model = new PostsJoin();
//        $transaction = static::getDb()->beginTransaction();
//        try {
//            foreach($data as $attributes)
//            {
//                $_model = clone $model;
//                $_model->setAttributes($attributes);
//                $_model->save();
//            }
//            $transaction->commit();
//            return true;
//        } catch (\yii\base\Exception $e) {
//            $transaction->rollBack();
//            return $e->getMessage();
//        }
        if(empty($data['group_id'])){
            $group = [];
        }else{
            $group = explode(',',$data['group_id']);
        }
        if(empty($data['item_id'])){
            $item = [];
        }else{
            $item = explode(',',$data['item_id']);
        }
        $value = [];
        if(count($group) > count($item)){
            foreach ($group as $k => $v){
                if(!empty($item[$k])){
                    $itemId = $item[$k];
                }else{
                    $itemId = '';
                }
                if(!empty($data['movie_id'])){
                    $movie = $data['movie_id'];
                    unset($data['movie_id']);
                }else{
                    $movie = '';
                }
                $value[] = [$data['posts_id'],$v,$itemId,$movie,time(),time()];
            }
        }else{
            if(empty($group) && empty($item)){
                $value[] = [$data['posts_id'],'','',$data['movie_id'],time(),time()];
            }else{
                foreach ($item as $k => $v){
                    if(!empty($group[$k])){
                        $groupId = $group[$k];
                    }else{
                        $groupId = '';
                    }
                    if(!empty($data['movie_id'])){
                        $movie = $data['movie_id'];
                        unset($data['movie_id']);
                    }else{
                        $movie = '';
                    }
                    $value[] = [$data['posts_id'],$groupId,$v,$movie,time(),time()];
                }
            }
        }
        $key = ['posts_id','group_id','item_id','movie_id','created_at','updated_at'];
        $res = \Yii::$app->db->createCommand()->batchInsert(PostsJoin::tableName(), $key, $value)->execute();
        return $res;
    }

    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findDataByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return bool
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
}
